import os
import re
import time
import datetime
import hashlib 

import mac2cred

def button(text,action,args=[]):
    return A(text,_href=URL(r=request,f=action,args=args), _class='button')

def buttonDownload(text,action,args=[]):
    return SPAN('[',A(text,_href=URL(c='static',f=action,args=args)),']')

def buttonIcon(icon,text,action,args=[]):
    #try to load png
    if os.path.exists(os.path.join(request.folder, 'static','images','btp','cop_icons', '%s.png' % icon)): 
        image=IMG(_src=URL(r=request,c='static', f=os.path.join('images','btp','cop_icons', '%s.png' % icon)), _width="64")
    elif os.path.exists(os.path.join(request.folder, 'static','images','btp','cop_icons', '%s.jpg' % icon)): 
        image=IMG(_src=URL(r=request,c='static', f=os.path.join('images','btp','cop_icons', '%s.jpg' % icon)), _width="64")       
    else:
        image=IMG(_src=URL(r=request,c='static', f=os.path.join('images','btp','cop_icons', 'noimage.jpg')), _width="64")
    temp=SPAN(text, _style='position:relative; top: -30px; padding-left:15px;')    
    return A([image,temp],_href=URL(r=request,f=action,args=args), _class='button')

def url(f,args=request.args,vars={}):
    return URL(r=request,f=f,args=args,vars=vars)

def goto(f,args=request.args,vars={},message='error'):
    session.flash=message
    redirect(url(f,args=args,vars=vars))

def error():
    goto('error')

def get(table, i=0, message='error'):
    try:
        id = int(request.args(i))
    except ValueError:
        goto('error',message=message)
    return table[id] or goto('error',message=message)

def link_client(client):
    return A(client.last_name,_href=url('showClient',client.id))

def link_contact(contact):
    return A(contact.last_name,_href=url('showContact',contact.id))

def link(text,action,args=[]):
    return SPAN(A(text,_href=URL(r=request,f=action,args=args)))

def pageIcon(link):
    linkName, linkExtension = os.path.splitext(link)
    if linkExtension:
        linkExtension=re.sub('\.', '', linkExtension)
        if os.path.exists(os.path.join(request.folder, 'static','images','extensions','%s.png' % linkExtension)): #Yay! Found nice icon
            return IMG(_src=URL(r=request,c='static', f=os.path.join('images','extensions','%s.png' % linkExtension)), _width="48")
        elif os.path.exists(os.path.join(request.folder, 'static','images','icons','file_extension_%s.png' % linkExtension)): #Mhm! Only found less nice icon but an icon nonetheless
            return IMG(_src=URL(r=request,c='static', f=os.path.join('images','icons','file_extension_%s.png' % linkExtension)), _width="48")
        else:
            return IMG(_src=URL(r=request,c='static', f=os.path.join('images','extensions','download.png')), _width="48")
    else: #no extension found; my best guess is that it's a link
        return IMG(_src=URL(r=request,c='static', f=os.path.join('images','extensions','isp.png')), _width="48")
    
def showQuiz(quiz, quiz_id):
    if quiz=='personal':
        content=db(db.quizpersonal.id==quiz_id).select().first()
    elif quiz=='regional':
        content=db(db.quizregional.id==quiz_id).select().first()
    else:
        content=False
    if content:
        myDict=dict(content=content)
        return response.render('emulator/show.html', myDict)
        #return dict(content=content)
    #No error handling needed??
    #else:
    #    redirect(URL('quiz', 'index'))
    
def md5_hash(text): 
    """ Generate a md5 hash with the given text """ 
    return hashlib.md5(text).hexdigest()

def addslashes(s):
    s = s.replace("'", "\\'")
    s = XML(s)
    return s

def resizeImage(fileName, size=100, fileLocation=False, fileExt="png", fileType="PNG"):
    try:    
        import os, uuid
        import os.path
        from PIL import Image
    except: return
    
    #fileDirectory = '%sstatic/images/thumbs/%s' % (request.folder, size)
    if fileLocation == False:
        fileLocation = '%sstatic/images/thumbs/%s/%s.%s' % (request.folder, size, os.path.splitext(fileName)[0], fileExt)
    
    d = os.path.dirname(fileLocation)
    if not os.path.exists(d):
        os.makedirs(d)

    resize=(size,size)
    try:
        im=Image.open(request.folder + 'uploads/' + fileName) 
    except: return
    im.thumbnail(resize,Image.ANTIALIAS)
    #thumbName='page.imageThumb.%s.png' % (uuid.uuid4())
    im.save(fileLocation, fileType, quality=95)
    return

def current_time():
    """Maincore uses this to get the current time to set the 'time_start'
    and 'time_end' values in the dbase table"""
    t = time.strftime("%y-%m-%d_%H:%M:%S", time.localtime())
    return t

def get_web2py_version():
    file_path = "VERSION"
    txt = open(file_path)
    line = txt.readline()
    version = line.split(" ")[1]
    return version
    
    